package cn.jfast.framework.jdbc.log;

import cn.jfast.framework.base.SDKVersion;
import cn.jfast.framework.log.LogFactory;
import cn.jfast.framework.log.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class SqlLogger implements InvocationHandler{

	private Logger log = LogFactory.getLogger(SqlLogger.class);
	private List<Object> params = new ArrayList<Object>();
	private String targetDao = "";
	private String sql = "";
    private java.sql.PreparedStatement ps;

    public SqlLogger(java.sql.PreparedStatement ps, String sql, String targetDao){
    	this.ps = ps;
		this.sql = sql;
		this.targetDao = targetDao;
    }

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		try {
			if (method.getName().startsWith("set"))
				params.add(args[1]);
			else if (method.getName().startsWith("execute"))
				log.info("[ JFast 版本号: %s ] 访问数据接口 : %s  打印SQL : %s", SDKVersion.version(),targetDao,String.format(sql, params.toArray()));
			return method.invoke(ps, args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
	}

}
